package com.example.bbs.web.servlet;

import com.alibaba.fastjson.JSON;
import com.example.bbs.model.Reply;
import com.example.bbs.model.User;
import com.example.bbs.service.PostService;
import com.example.bbs.service.ReplyService;
import com.example.bbs.service.impl.PostServiceImpl;
import com.example.bbs.service.impl.ReplyServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@WebServlet(name = "PubReplyServlet", value = "/bbs/doPubReply")
public class PubReplyServlet extends HttpServlet {
    private PostService postService = new PostServiceImpl();
    private ReplyService replyService = new ReplyServiceImpl();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        int pid = Integer.parseInt(req.getParameter("pid"));
        String content = req.getParameter("content");
        HttpSession session = req.getSession();
        User user = (User) session.getAttribute("loginUser");
        Reply reply = new Reply(pid,user.getUserId(),content);
        boolean bool = replyService.addReply(reply);
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("text/html; charset=utf-8");

        //将用户信息和回复对象发送给客户端
        Map<String,Object> jsonMap = new HashMap<>();
        jsonMap.put("user",user);
        jsonMap.put("reply",reply);

       String json = JSON.toJSONStringWithDateFormat(jsonMap,"yyyy-MM-dd HH:mm:ss");
       resp.getWriter().write(json);
    }
}
